import java.text.DecimalFormat
import java.text.SimpleDateFormat
import java.util.*

private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
private const val K_SIZE = 1024L
private const val M_SIZE = K_SIZE * K_SIZE
private const val G_SIZE = M_SIZE * K_SIZE
private const val B = "B"
private const val K = "KB"
private const val M = "MB"
private const val G = "GB"

/**
 * 将字节数据转为带单位的字符串
 * @param fileSize 文件字节大小
 * @return 带单位的字符串
 */
fun formatFileSize(fileSize: Long): String {
    val fileSizeStr: String
    if (fileSize == 0L) {
        return "0$B"
    }
    // 小数位数自定义
    val df = DecimalFormat("#.##")
    fileSizeStr = if (fileSize < K_SIZE) {
        df.format(fileSize.toDouble()) + B
    } else if (fileSize < M_SIZE) {
        df.format(fileSize.toDouble() / K_SIZE) + K
    } else if (fileSize < G_SIZE) {
        df.format(fileSize.toDouble() / M_SIZE) + M
    } else {
        df.format(fileSize.toDouble() / G_SIZE) + G
    }
    return fileSizeStr
}

fun time(): String = dateFormat.format(Date())

fun printMessage(message: String) {
    println("${time()}  $message")
}

fun printMessage(sb: StringBuilder, message: String) {
    sb.append(time()).append("  ").append(message).append("\n")
    printMessage(message)
}
